package com.sjc.designpattern.observer;

import java.util.Observable;
import java.util.Observer;

/**
 * @Classname ObserverPatternDemo
 * @Description 观察者模式：监听目标对象的状态改变
 * 1. zookeeper 分布式锁
 * 2. 系统A调用系统B，监听系统B的变化
 * @Date 2020/4/25 21:45
 * @Created by SangJiacun
 */
public class ObserverPatternDemo {
    public static void main(String[] args) {
        Subject subject = new Subject(0);

        ConcreteObserver concreteObserver = new ConcreteObserver();
        subject.addObserver(concreteObserver);

        subject.setState(1);
        subject.setState(2);
    }

    public static class Subject extends Observable{
        private Integer state;

        public Subject(Integer state) {
            this.state = state;
        }

        public Integer getState() {
            return state;
        }

        public void setState(Integer state) {
            // 在这里状态就改变了
            this.state = state;
            // 通知关联的一些观察者，说我的状态变化了
            this.setChanged();
            this.notifyObservers();
        }
    }

    public static class ConcreteObserver implements Observer{

        @Override
        public void update(Observable o, Object arg) {
            Subject subject = (Subject) o;
            Integer state = subject.getState();
            System.out.println("目标对象的状态变化成：" + state);
        }
    }

}
